﻿$.widget("socaloud.tweetDetailsWidget", {

    options: {
        template: 'templates/tweet-details-template.html'
    },

    _create: function () {
        var self = this;

        var content = Extension.getTemplate(self.options.template);
        self.element.append(content);

        self.options.viewModel = {
            id: self.options.id,
            replyText: ko.observable(''),
            details: ko.observable({}),
            replies: ko.observableArray([])
        };

        ko.applyBindings(self.options.viewModel, self.element[0]);

        Repository.Twitter.getTweetDetails(self.options.viewModel.id, function (data) {
            if (!!data) {
                self.options.viewModel.details(data || {});
                if (!!data.user) {
                    self.options.viewModel.replyText('@' + data.user.screen_name+' ');
                }
            }
        });

        Repository.Twitter.getTweetReplies(self.options.viewModel.id, function (data) {
            if (!!data) {
                self.options.viewModel.replies(data || []);
            }
        });

        $(self.element).on('click', '#reply-btn', function () {
            var reply = $('#reply-box', self.element).val();
            if (!!self.options.viewModel.id && !!reply) {
                Repository.Twitter.reply(self.options.viewModel.id, reply, function () {
                    alert('replied');
                });
            }
        });

    },

    _destroy: function () {
        this.element.html('');
    }
});